package com.znjc.device.service;


import com.znjc.common.constant.DeviceConstants;
import com.znjc.device.domain.IotDataCheck;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.websocket.WebSocketUsers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 数据采集任务服务
 * 负责执行具体的采集任务逻辑
 */
@Slf4j
@Service
public class DataCollectorService {

    @Autowired
    private SerialPortService serialPortService;

    @Autowired
    private IIotDataCheckService iotDataCheckService;

    @Autowired
    private DataStorageService dataStorageService;

    /**
     * 执行单个采集任务
     * 这个方法会被定时任务调用
     */
    @Async
    public CompletableFuture<Boolean> executeCollectionTask(IotSerial iotSerial) {
        log.info("开始执行采集任务，串口: {}", iotSerial.getSerialCode());
        WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"开始执行采集任务，串口: {}"+iotSerial.getSerialCode());

        try {
            // 1. 获取该串口对应的所有采集命令
            List<IotDataCheck> commands = iotDataCheckService.getIotDataCheckListBySerialId(iotSerial.getId());

            if (commands.isEmpty()) {
                WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"串口 {} 没有配置采集命令"+ iotSerial.getSerialCode());
                return CompletableFuture.completedFuture(false);
            }

            // 2. 按顺序执行每个采集命令
            for (IotDataCheck command : commands) {
                if (!executeSingleCommand(command, iotSerial)) {
                    WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"命令"+command.getCheckName()+"执行失败，继续下一个命令");
                    // 继续执行下一个命令，不中断整个任务
                }

                // 命令间短暂间隔
                Thread.sleep(100);
            }

            WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"采集任务执行完成");
            return CompletableFuture.completedFuture(true);

        } catch (Exception e) {
            WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"采集任务执行异常: {}"+e.getMessage());
            return CompletableFuture.completedFuture(false);
        }
    }

    /**
     * 执行单个命令
     * @param command 采集命令
     * @param iotSerial 串口配置
     * @return 是否执行成功
     */
    private boolean executeSingleCommand(IotDataCheck command, IotSerial iotSerial) {
        log.info("执行命令: {}", command.getCheckName());

        try {
            // 1. 发送命令
            Date date = new Date();
            if (!serialPortService.sendCommand(command.getCommand())) {
                log.error("命令发送失败: {}", command.getCheckName());
                WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"命令发送失败: {}"+command.getCheckName()+command.getCommand());
                return false;
            }

            // 2. 等待响应（超时10秒）
            String response = serialPortService.waitForResponse(10);

            if (response == null) {
                log.warn("命令 {} 响应超时", command.getCheckName());
                WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,"命令 {} 响应超时"+command.getCheckName()+command.getCommand());
                return false;
            }

            // 3. 处理响应数据
            return processResponseData(command, response, iotSerial,date);

        } catch (Exception e) {
            log.error("执行命令异常 {}: {}", command.getCheckName(), e.getMessage(), e);
            WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996, command.getCheckName()+e.getMessage());
            return false;
        }
    }

    /**
     * 处理响应数据
     */
    private boolean processResponseData(IotDataCheck command, String response, IotSerial iotSerial, Date date) {
        try {
            // 存储数据
            dataStorageService.saveCollectionData(iotSerial, command, response,date);
            log.info("命令 {} 数据存储成功", command.getCheckName());
            WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996,command.getCheckName());
            return true;
        } catch (Exception e) {
            log.error("处理响应数据异常: {}", e.getMessage(), e);
            WebSocketUsers.sendMessageToUserByText(DeviceConstants.VUE_MSG_CLINET_9996, e.getMessage());
            return false;
        }
    }


}
